<template>
  <div class="login">
    <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="login-form">
      <h3 class="title">五育综合数据平台</h3>
      <div>
        <el-form-item prop="studentId">
          <el-input prefix-icon="User" type="text" v-model="ruleForm.studentId" placeholder="账号(学号/教工号)" size="large"
            class="input-center" />
        </el-form-item>
        <el-form-item prop="password">
          <el-input prefix-icon="Lock" type="password" v-model="ruleForm.password" placeholder="密码" autocomplete="off"
            size="large" class="input-center" />
        </el-form-item>
        <el-form-item class="submitBtn">
          <el-button type="primary" :loading="loading" style="width: 100%;" @click="submitForm('ruleForm')">登录
          </el-button>
        </el-form-item>
      </div>
    </el-form>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    const validateStudentId = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入学号'));
      } else {
        callback();
      }
    };
    const validatePass = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入密码'));
      } else {
        callback();
      }
    };

    return {
      ruleForm: {
        studentId: '',
        password: ''
      },
      rules: {
        studentId: [{ validator: validateStudentId, trigger: 'blur' }],
        password: [{ validator: validatePass, trigger: 'blur' }]
      }, loading: false,


    };
  },
    created() {
    this.checkToken();
  },
  methods: {
    checkToken() {
      const token = sessionStorage.getItem('authToken');
      const studentId = sessionStorage.getItem('studentId');

      if (token && studentId) {
        axios.post('http://47.238.86.58:5000/validate-token', { token, studentId })
          .then(response => {
            if (response.data.code === 200) {
              // Token 有效，跳转到 /start
              this.$router.push('/start');
            }
          })
          .catch(error => {
            console.error('Token 验证失败:', error);
          });
      }
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        this.loading = true;
        if (valid) {
          // 获取表单数据
          const formData = {
            studentId: this.ruleForm.studentId,
            password: this.ruleForm.password,
          };

          // 使用 axios 发送 POST 请求到后端
          axios.post('http://47.238.86.58:5000/login', formData)
            .then((response) => {
              // 根据后端返回的 code 和 msg 进行判断
              const { code, msg, token } = response.data;
              // 如果登录成功
              if (code === 200) {
                // 如果 code 为 200，表示登录成功
                this.$message({
                  message: '登录成功！',
                  type: 'success',
                });
                // 保存 token 到 localStorage 中
                sessionStorage.setItem('authToken', token);
                sessionStorage.setItem('studentId', this.ruleForm.studentId);
                // 你可以在这里进行页面跳转或其他操作
                this.$router.push('/start');
              } else if (code === 500) {
                this.loading = false;
                // 如果 code 为 500，显示用户不存在/密码错误的提示
                this.$message({
                  message: msg || '用户不存在或密码错误',
                  type: 'error'
                });
              }
            })
            .catch((error) => {
              // 处理错误
              this.loading = false;
              this.$message({
                message: '登录失败，请检查网络！ ',
                type: 'error'
              });
              console.error(error);
            });

        } else {
          this.loading = false;
          console.log('提交失败！');
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    }
  }
}

</script>
<style>
body {
  background-image: url('/background.jpg');
  background-size: cover;
  /* 使背景图片覆盖整个页面 */
  background-repeat: no-repeat;
  /* 不重复背景图片 */
  height: 100vh;
  /* 确保高度为视口高度 */
  margin: 0;
  /* 清除默认边距 */
}
</style>
<style scoped>
.login {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
}


.login-form {
  width: 380px;
  background: white;
  border-radius: 5px;
  padding: 25px;
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
  margin-bottom: 22px;
}

.title {
  text-align: center;
  margin-bottom: 30px;
}

/* 使用 deep 选择器来覆盖默认样式 */
:deep(.el-form-item__content) {
  margin-left: 0 !important;
}

@font-face {
  font-family: 'MyCustomFont';
  src: url('@/assets/fonts/element-icons.535877f5.woff') format('woff');
  font-weight: normal;
  font-style: normal;
}
</style>
